package com.huoyun.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

	public static final String FORMAT_YMD = "yyyyMMdd";

	public static final String FORMAT_YDMHMS = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 
	 * 把日期转换为字符串
	 * 
	 * 
	 * 
	 * @param date
	 * 
	 *            日期实例
	 * 
	 * @param format
	 * 
	 *            日期格式
	 * 
	 * @return Date
	 */

	public static String dateToStr(Date date, String format) {

		return (date == null) ? "" : new SimpleDateFormat(format).format(date);

	}

	public static String dateToStr(Date date) {

		return (date == null) ? ""
				: new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);

	}

	/**
	 * 
	 * 取得当前日期 年月日
	 * 
	 * 
	 * 
	 * @return Date
	 */

	public static String getCurrentDate() {

		DateFormat f = new SimpleDateFormat("yyyyMMdd");

		return f.format(Calendar.getInstance().getTime());

	}
	
	/**
	 * 按不同时段定制日期格式(与当前时间比较)
	 * 小于1小时：mm分钟前
	 * 当天：今天HH:mm
	 * 昨天：昨天HH:mm
	 * 小于一年：MM-dd HH:mm
	 * 大于一年：yyyy-MM-dd HH:mm
	 * @param date
	 * @return 时间字符串
	 */
	public static String getDateStrForPeriod(Date date)
	{
		String dateStr;
		
		Calendar currCalendar = Calendar.getInstance();
		Calendar paraCalendar = Calendar.getInstance();
		currCalendar.setTime(new Date());
		paraCalendar.setTime(date);
		
		if (currCalendar.get(Calendar.YEAR) == paraCalendar.get(Calendar.YEAR))
		{
			if (currCalendar.get(Calendar.MONTH) == paraCalendar.get(Calendar.MONTH))
			{
				if (currCalendar.get(Calendar.DAY_OF_MONTH) == paraCalendar.get(Calendar.DAY_OF_MONTH))
				{
					if ((currCalendar.getTimeInMillis() - paraCalendar.getTimeInMillis()) < 3600000)
					{
						dateStr = (currCalendar.getTimeInMillis() - paraCalendar.getTimeInMillis())/60000 + "分钟前";
					}
					else
					{
						dateStr = "今天 " + (new SimpleDateFormat("HH:mm").format(paraCalendar.getTime()));
					}
				}
				else if (currCalendar.get(Calendar.DAY_OF_MONTH) == (paraCalendar.get(Calendar.DAY_OF_MONTH)+1))
				{
					dateStr = "昨天 " + (new SimpleDateFormat("HH:mm").format(paraCalendar.getTime()));
				}
				else
				{
					dateStr = new SimpleDateFormat("MM-dd HH:mm").format(paraCalendar.getTime());
				}
			}
			else
			{
				dateStr = new SimpleDateFormat("MM-dd HH:mm").format(paraCalendar.getTime());
			}
		}
		else
		{
			dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(paraCalendar.getTime());
		}
		
		return dateStr;
	}
}
